/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.AutoDocumentTransaction;
import wads.com.WADTools;

public class SearchDocument extends HttpServlet {
  private static final long serialVersionUID = -1725895851140213003L;

  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;

  /**Initialize global variables*/
  HttpSession session;
  String app_Path;


  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    session = request.getSession(false);
    String userName = (String)session.getAttribute("UserName");

    System.out.println(userName);
    //app_Path = this.getInitParameter("app_Path");
    app_Path = WADTools.APP_PATH;

    ServletOutputStream sos = response.getOutputStream();
    try{
      File User = new File(app_Path+"res/docs/InProgressAutoDoc/" + userName);
      ObjectOutputStream oos = new ObjectOutputStream((OutputStream)sos);
      if(User.exists()){
      String[] FileList = User.list();
        for(int i=0; i<FileList.length; i++){
          //Read Object AutoDocumentTransaction
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/InProgressAutoDoc/" + userName + "/" + FileList[i]));

          AutoDocumentTransaction adTran = (AutoDocumentTransaction)ois.readObject();

          int status = adTran.getDocumentStatus();
          String sta = null;
          if(status == 1){
            //sta = String.valueOf(status);
            sta = "1";
          }
          else{
            sta = "0";
          }
          String Name = adTran.getOwner_Name();
          oos.writeObject(sta);
          oos.writeObject(Name);
          oos.writeObject(FileList[i]);
          ois.close();
        }
      }
    }catch(Exception e) {
      sos.println(e.toString());
    }
  }
}